#include "cocos2d.h"
#include "Tank1.h"
#include "global.h"
using namespace cocos2d;
float Tank1::juli(CCPoint o1,CCPoint o2)
{
    return sqrt((o1.x-o2.x)*(o1.x-o2.x)+(o1.y-o2.y)*(o1.y-o2.y));
}
int  Tank1::too2(CCPoint o1, CCPoint o2)
{
    int dir;
    if (fabs(o1.x - o2.x) < fabs(o1.y - o2.y))
    {
        if (o1.y < o2.y)
        {
            //down
                dir=1;
            }
            else
            {
                dir =2;
                
            }
			}
			else
			{
				if (o1.x < o2.x)
				{
					//right
					dir=4;
				}
				else
				{
					dir = 3;
				}
				
			}
    return dir;
}
void Tank1::changedir()
{
	int i = dir;
	while (i == dir)
		i = floor(((float)rand()/(RAND_MAX+1.0)) * 4) + 1;
	dir=i;//lasttime=0;
}
void Tank1::update(float dt)
{
    the = this->getPosition();
	if (!global_run)
	{

		return ;
	}

	time+=dt;
	lasttime+=dt;
    
	if (time >2)
        {
            shot();
            time=0;
        }
	if(lasttime>3)
	{
        lasttime=0;
        if(global_difficult)
		{//changedir();//change direction
            if (global_myTank == NULL)
            {
            }
            else
            {
                if(juli(the,global_myTank->getPosition())<juli(the,home))
                {
                dir = too2(the, global_myTank->getPosition());
                }
                else
                {
                    dir=too2(the,home);
                }
                //the.gotoAndStop(dir);
                
            }
        
        }
        else
        {
            changedir();
            
        }
    }
	switch (dir)
	{
	case 1: 
		{
			if (tryMoveUp(dt*speed))
				;
			else
				changedir();
			break;
		}
	case 2: 
		{
			if (tryMoveDown(dt*speed))
				;//the.y += speed;
			else
				changedir();//the.gotoAndStop(i);
			break;
		}
	case 3: 
		{
			if (tryMoveLeft(dt*speed))
				;//the.x -= speed;
			else
				changedir();//the.gotoAndStop(i);
			break;
		}
	case 4: 
		{
			if (tryMoveRight(dt*speed))
				;//the.x += speed;
			else
				changedir();//the.gotoAndStop(i);
			break;
		}
	default: 
		break;
	}

}
Tank1::Tank1(float x, float y):Tank("tank1.png",x,y)
{
	theid = 1;
	speed = 2.0/2*60;
	score = 100;
	time=0;
	lasttime=0;
    //chktime=0;
    home=ccp(208,16);
}
Tank1::Tank1(const char * filepath,float x, float y):Tank(filepath,x,y)
{
	
	theid = 1;
	speed = 2.0/2*60;
	score = 100;
	time=0;
	lasttime=0;
    home=ccp(208,16);
    //chktime=0;
}
Tank2::Tank2(float x, float y):Tank1("tank2.png",x,y)
{
	speed = 3.0/2*60;
	score = 200;
}
Tank3::Tank3(float x, float y):Tank1("tank3.png",x,y)
{
	speed = 1/2.0*60;
	life = 3;
	score = 300;
}
